/**
 * Created by Weizehua on 2017/1/17.
 */
import {Injectable} from "@angular/core";
import {ServerInfoService} from "./ServerInfoService";
import {UserService} from "./UserService";

@Injectable()
export class RequestService {
    constructor(private serverInfo: ServerInfoService, private userInfo: UserService) {
    }

    get(path: string, params: {[name: string]: string|number|Date} = {}): Promise<any> {
        console.log(`request : ${path}, param : `);
        console.log(params);
        return new Promise<any>((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.open('POST', this.serverInfo.buildRequestPath(path), true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify({userInfo: this.userInfo.userInfo, params: params}));
            xhr.onreadystatechange = () => {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        let res = JSON.parse(xhr.responseText);
                        if (res.success)
                            resolve(res);
                        else
                            reject(res.reason);
                        console.log(res);
                    }
                    else {
                        reject(`Request ${path} finished with error status: (${xhr.status}) ${xhr.statusText}`);
                    }
                }
            };
            xhr.onabort = ev => reject(ev);
            xhr.onerror = ev => reject(ev);
        })
    }

    /*
     get(path: string, params: {[name: string]: string}): Promise<any> {
     window['myhttp'] = HTTP;
     let data = {userInfo: this.userInfo.userInfo, params: params};
     window['mydata'] = data;
     console.log(data);
     console.log("stringify:", JSON.stringify(data));
     return new Promise<any>((resolve, _) => {
     HTTP.post(this.serverInfo.buildRequestPath(path), JSON.stringify(data), {}).then((response: HTTPResponse) => {
     let data = response.data;
     let obj = JSON.parse(data);
     resolve(obj);
     });
     });
     }
     */
}

